import { useUser } from "@/hook/useUser/useUser"
import { user } from "@/servers/user"
import { Card, Flex, message, Button, Form, Input, Typography, Space } from "antd"
import { LoginOutlined, MailOutlined, SafetyCertificateOutlined, SendOutlined, InfoCircleOutlined } from "@ant-design/icons"
import { useEffect, useState } from "react";
import { useNavigate } from "react-router";

const { Text } = Typography;

export default function UserLogin() {
  const { login, isLoggedIn } = useUser();

  // 如果已经登录，跳转到用户首页
  useEffect(() => {
    if (isLoggedIn) {
      navigate("/user");
    }
  }, [])

  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(() => {
    const endTimeStr = localStorage.getItem("countdownEndTime");
    if (!endTimeStr) return 0;

    const endTime = parseInt(endTimeStr, 10);
    const now = Date.now();

    // 如果当前时间大于结束时间，清除存储的结束时间
    if (now > endTime) {
      localStorage.removeItem("countdownEndTime");
      return 0;
    }

    return Math.floor((endTime - now) / 1000);
  });


  useEffect(() => {
    if (countdown <= 0) return;

    // 设置定时器，若倒计时仍在进行中，则继续倒计时
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          localStorage.removeItem("countdownEndTime");
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => {
      clearInterval(timer);
    }

  }, [countdown > 0])

  const handleSendCode = async () => {
    try {
      await form.validateFields(["email"]);
      setSending(true);
      const email = form.getFieldValue("email");
      await user.sendCode(email);
      message.success("验证码发送成功，请注意查收");

      // 设置倒计时结束时间
      const endTime = Date.now() + 60 * 1000;
      localStorage.setItem("countdownEndTime", endTime.toString());
      setCountdown(60);
    } catch (error) {
      if (error.errorFields) {
        // 表单验证失败
        return;
      }
      message.error("发送验证码失败，请稍后再试");
    } finally {
      setSending(false);

    }
  }

  const onFinish = async (values) => {
    try {
      setLoading(true);
      const { email, code } = values;
      await login(email, code);
      message.success("登录成功，2秒后跳转至用户首页");
      setTimeout(() => {
        navigate("/user");
      }, 2000);
    } catch (error) {
      message.error("登录失败，请稍后再试");
    } finally {
      setLoading(false);
    }

  };

  return <Card title={
    <span><LoginOutlined style={{
      marginRight: "8px"
    }} />用户登录</span>

  } style={{ width: "800px" }}>
    <Form
      name="basic"
      form={form}
      wrapperCol={{ span: 16 }}
      style={{ margin: "0 auto" }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      autoComplete="off"
    >
      <Form.Item
        name="email"
        rules={[{ required: true, message: '请输入邮箱!' }, { type: 'email', message: '请输入正确的邮箱格式!' }]}
      >
        <Input prefix={<MailOutlined />} placeholder="请输入邮箱" />
      </Form.Item>

      <Form.Item
        name="code"
        rules={[{ required: true, message: '请输入验证码!' }]}
      >
        <Flex gap="15px" style={{ width: "100%" }}>
          <Input
            prefix={<SafetyCertificateOutlined />}
            placeholder="请输入验证码"
            style={{ flex: 1 }}
          />
          <Button onClick={handleSendCode} disabled={countdown > 0} loading={sending} type="primary"
            icon={<SendOutlined />}>
            {countdown > 0 ? `${countdown}秒后重发` : "发送验证码"}
          </Button>
        </Flex>
      </Form.Item>
      <Space align="center" style={{ marginBottom: "16px" }}>
            <InfoCircleOutlined style={{ color: "#1677ff", fontSize: "12px" }} />
            <Text type="secondary" style={{ fontSize: "12px" }}>
              没有注册过的邮箱会自动注册一个账号
            </Text>
          </Space>
      <Form.Item label={null}>
        <Button type="primary" htmlType="submit" loading={loading} icon={<LoginOutlined />}>
          登录
        </Button>
      </Form.Item>
    </Form>
  </Card>
}